/**
 *  Copyright Matt Silbernagel 2010
 *  
 *	This file is part of MobilePrinting.
 *
 *	MobilePrinting is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  MobilePrinting is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MobilePrinting.  If not, see <http://www.gnu.org/licenses/>.
 */

package edu.uc.labs.MobilePrinting.GUI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.apache.log4j.Logger;
import org.xml.sax.SAXException;

import edu.uc.labs.MobilePrinting.Configurator;
import edu.uc.labs.MobilePrinting.OSUtils.StartupManager;
import edu.uc.labs.MobilePrinting.Prefs.Preferences;
import edu.uc.labs.MobilePrinting.Prefs.PreferencesParser;
import edu.uc.labs.MobilePrinting.Prefs.PreferencesWriter;
import edu.uc.labs.MobilePrinting.PrintUtils.Printer;
import edu.uc.labs.MobilePrinting.PrintUtils.PrinterManager;
import edu.uc.labs.MobilePrinting.PrintUtils.PrinterWriter;

public class PreferencesFrame extends JFrame implements ActionListener {

	private static Logger logger = Configurator.LOGGER;
	private static final long serialVersionUID = -2051525508610402431L;
	private PreferencesPanel p;
	private Preferences userPrefs;
	private Preferences defaultPrefs;

	public PreferencesFrame( PreferencesPanel prefPanel ) {
		// Name the window
		super("Mobile Printing Preferences");
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);

		// Set up the close/cancel button
		closeButton = new JButton();
		closeButton.addActionListener(this);
		closeButton.setActionCommand("Close");
		closeButton.setText("Cancel");

		// Set up the save button
		saveButton = new JButton();
		saveButton.addActionListener(this);
		saveButton.setActionCommand("Save");
		saveButton.setText("Save");

		// Set up the defaults button
		defaultsButton = new JButton();
		defaultsButton.addActionListener(this);
		defaultsButton.setActionCommand("Defaults");
		defaultsButton.setText("Restore Defaults");

		// Setup the button pane
		JPanel buttonPane = new JPanel();
		buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
		buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
		buttonPane.add(Box.createHorizontalGlue());
		buttonPane.add(closeButton);
		buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
		buttonPane.add(saveButton);

		// Place the button near the bottom of the window.
		Container contentPane = getContentPane();
		contentPane.add(buttonPane, BorderLayout.PAGE_END);
		
		userPrefs = new Preferences();
		PreferencesParser parser;
		try {
			parser = new PreferencesParser();
			defaultPrefs = parser.parse( new File(Configurator.default_prefs) );
		} catch (ParserConfigurationException e) {
			logger.error( e.toString() );
			defaultPrefs = new Preferences();
		} catch (XPathExpressionException e) {
			logger.error(e.toString() );
			defaultPrefs = new Preferences();
		} catch (SAXException e) {
			logger.error( e.toString() );
			defaultPrefs = new Preferences();
		} catch (IOException e) {
			logger.error( e.toString() );
			defaultPrefs = new Preferences();
		}
		
		p = prefPanel;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		
		if ("Close".equals(e.getActionCommand())) {
			// if the close button was clicked...
			setVisible(false);
			dispose();
			PreferencesPanel.isOpen = false;
		}

		if ("Save".equals(e.getActionCommand())) {
			// the save button was clicked
			logger.debug("The save button was clicked");
			
			String newPrinterName = p.printerNameText.getText();
			String pName = Configurator.PRINTERNAME;
			if(edu.uc.labs.MobilePrinting.OSUtils.SanityCheck.isPrinterNameValid(newPrinterName)) {
				logger.debug("The printer name doesn't have invalid charactors, continue processing...");
				userPrefs.setPrinterName(newPrinterName);
				if (!pName.equalsIgnoreCase(userPrefs.getPrinterName())){	
					logger.debug("The printer name needs to be changed...");
					Configurator.PRINTERNAME = userPrefs.getPrinterName();
					Printer printer = PrinterWriter.getCurrent();
					if (!printer.isEmpty()){
						PrinterManager prnManager = new PrinterManager(printer);
						logger.debug("The user wants to rename the printer from " + pName + " to " + userPrefs.getPrinterName());
						prnManager.renamePrinter(pName, userPrefs.getPrinterName());
					}
				}
				
				userPrefs.setConfigServer(p.confServerText.getText());
				String level = (String) p.logComboBox.getSelectedItem();
				logger.debug("Log level should be set to " + level + ": Setting now..." );
				userPrefs.setLogLevel( level );
				Configurator.setLogLevel(level);
					
				userPrefs.setAutoUpdate( boolToString( p.updateCheckBox.isSelected() )); 
				userPrefs.setDeleteOnExit( boolToString(p.deletePrinterCheckBox.isSelected() ));
				userPrefs.setStartAtLogin( boolToString(p.startCheckBox.isSelected() ));
				logger.debug("The new Preferences: \n" + userPrefs.toString());
				try {
					PreferencesWriter pwriter = new PreferencesWriter(userPrefs);
					pwriter.write();
				} catch (ParserConfigurationException e1) {
					logger.error(e1.toString());
				} catch (IOException e1) {
					logger.error(e1.toString());
				}
				
				StartupManager sm = new StartupManager();
				sm.execute( userPrefs );
				this.setVisible(false);
				PreferencesPanel.isOpen = false;
				dispose();
			} else {
				logger.debug("The printer name has invalid charactors...");
				p.printerNameLabel.setText("Printer Name - Can only contain letters and numbers - Please choose another name");
				p.printerNameLabel.setForeground(Color.RED);
				this.getContentPane().repaint();
			}
			
			
			
			
		}

		if ("Defaults".equals(e.getActionCommand())) {
			// the defaults button was clicked
			
			//set advanced features
			p.confServerText.setText(defaultPrefs.getConfigServer());
			p.logComboBox.setSelectedItem(defaultPrefs.getLogLevel());
			p.printerNameText.setText(defaultPrefs.getPrinterName());
			
			//set general settings
			p.startCheckBox.setSelected(defaultPrefs.isStartAtLogin());
			p.updateCheckBox.setSelected(defaultPrefs.isAutoUpdate());
			p.deletePrinterCheckBox.setSelected(defaultPrefs.isDeleteOnExit());
		}
	}

	public void addCloseButton() {
		Container contentPane = getContentPane();
		contentPane.add(closeButton);
		closeButton.setAlignmentX(Component.CENTER_ALIGNMENT); // horizontally
															   // centered
	}

	public void addSaveButton() {
		Container contentPane = getContentPane();
		contentPane.add(saveButton);
		saveButton.setAlignmentX(Component.CENTER_ALIGNMENT);

	}
	
	private String boolToString( boolean b ){
		String num = b ? "1" : "0";
		return num;
	}

	// Variable Declaration
	JButton closeButton;
	JButton saveButton;
	JButton defaultsButton;
}
